package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class StatementItemServiceImpl implements IStatementItemService {
    @Autowired
    private StatementItemMapper statementItemMapper;

    @Autowired
    private IStatementService statementService;

    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        //PageHelper 封装页面
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectFcrList(qo));
    }

    @Override
    public void save(List<StatementItem> statementItems) {
        //先判断状态 删除并获取最后一条的记录
        StatementItem temp = statementItems.remove(statementItems.size() - 1);
        //获取商品折扣价价格
        BigDecimal discountAmount = temp.getItemPrice();
        //获取结算单对象
        Statement statement = statementService.get(temp.getStatementId());
        //根据结算单ID获取结算单对象,进行合理性判断.(处于消费中才能保存明细)
        //已支付抛出异常
        if(Statement.STATUS_PAID.equals(statement.getStatus())){
            throw new BusinessException("不能对已支付的结算单进行明细操作");
        }
        //删除之前的明细项   消费状态还可以进行编辑(所以再次编辑之前把上一次的数据在数据库中删除)
        statementItemMapper.deleteItemsByStatementId(statement.getId());
        //定义总金额,总数量的变量(统计明细项中的金额和数量)
        //总金额 = SUM(明细项单价*数量)
        BigDecimal totalAmount = new BigDecimal(0);
        //总数量 = SUM(数量)
        BigDecimal totalQuantity = new BigDecimal(0);
        //循环过程中把明细项插入明细表中
        if(statementItems.size()>0){
            //有数据说明有明细项 并把明细项插入明细表中
            for (StatementItem item : statementItems) {
                statementItemMapper.insert(item);
                //总金额 = SUM(明细项单价*数量)
                //multiply乘
                totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
                //总数量 = SUM(数量)
                totalQuantity = totalQuantity.add(item.getItemQuantity());
            }
        }
        //判断折扣金额的合理性  如果优惠金额比总金额还要更多，属于非法逻辑
        //compareTo相比较
        if(totalAmount.compareTo(discountAmount)<0){
            throw new BusinessException("非法操作,优惠金额大于总金额");
        }
        //保存(更新进行修改)更新结算单的总金额,总数量,折扣价
        statementService.updateAmount(ShiroUtils.getUserId(),statement.getId(),totalAmount,totalQuantity,discountAmount);
    }

}
